<?php

App::uses('Crud', 'Model');
App::uses('Categorization', 'Model');
App::uses('Line', 'Model');
App::uses('Area', 'Model');
App::uses('UserArea', 'Model');
App::uses('UserTest', 'Model');
App::uses('Moe', 'Model');
App::uses('User', 'Model');
App::uses('Schedule', 'Model');

class UserLine extends Crud
{

    const STATUS_DISABLED = 0;
    const STATUS_ENABLED = 1;
    public $useTable = 'user_lines';

    /**
     * Obtenemos todos registros habilitados.
     * @return array
     */
    public function getAll()
    {
        $filters = array(
            'order' => array('assign_date' => 'ASC'),
            'conditions' => array('status' => self::STATUS_ENABLED)
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    /**
     * Obtenemos todos registros habilitados.
     * @return array
     */
    public function getbyUser($userId)
    {
        $filters = array(
            'conditions' => array(
                'user_id' => $userId,
                'status' => self::STATUS_ENABLED
            ),
            'order' => array('assign_date' => 'ASC'),
        );
        $records = $this->find('all', $filters);

        return $this->flatArray($records);
    }

    public function getbyUserLine($model)
    {
        $filters = array(
            'conditions' => array(
                'user_id' => $model->user_id,
                'line_id' => $model->line_id,
                'status' => self::STATUS_ENABLED
            ),
            'order' => array('assign_date' => 'ASC'),
        );
        return $this->find('count', $filters);
    }

    /**
     * Obtenemos los usuarios asociados a una linea
     * @param string $lineId UUID
     */
    public function getByLine($lineId)
    {
        $filters = array(
            'fields' => array(
                'User.id as value',
                'User.full_name as text',
            ),
            'joins' => array(
                array(
                    'table' => 'us3rs_r4gg14n4',
                    'alias' => 'User',
                    'join' => 'INNER',
                    'conditions' => array(
                        'User.id = UserLine.user_id'
                    ),
                ),
            ),
            'conditions' => array(
                'UserLine.line_id' => $lineId,
                'UserLine.status' => self::STATUS_ENABLED
            ),
        );
        $records = $this->flatArray($this->find('all', $filters));
        return $records;
    }

    /**
     * Actualizamos el nivel (categoria) de un usuario para una linea.
     * @param string $userId UUID
     * @param string $lineId UUID
     * @param integer $newLevel
     */
//

    public function getByUserAndLine($userId, $lineId)
    {
        $filters = array(
            'conditions' => array(
                'user_id' => $userId,
                'line_id' => $lineId,
                'status' => self::STATUS_ENABLED
            ),
            'order' => array('assign_date' => 'ASC'),
        );
        return $this->find('first', $filters);
    }

    public function getByUserAndArea($user)
    {

    }

    public function getLineCategorization($uId = 0)
    {
        $filters = array(
            'joins' => array(
                array(
                    'table' => 'us3rs_r4gg14n4 as u',
                    'type' => 'inner',
                    'conditions' => array(
                        'u.id = UserLine.user_id',
                        'u.status' => array(User::STATUS_ENABLED, User::STATUS_INCAPACIDAD, User::STATUS_VACACIONES)
                    )
                ),
                array(
                    'table' => 'lines',
                    'type' => 'left',
                    'conditions' => array(
                        'lines.id = UserLine.line_id',
                        'lines.status' => Line::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'areas',
                    'type' => 'inner',
                    'conditions' => array(
                        'areas.id = lines.area_id',
                        'areas.status' => Area::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'moes',
                    'type' => 'inner',
                    'conditions' => array(
                        'moes.id = areas.moe_id',
                        'moes.status' => Moe::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'categorizations',
                    'type' => 'inner',
                    'conditions' => array(
                        'categorizations.id = UserLine.level',
                        //'categorizations.status' => Categorization::STATUS_ENABLED
                    )
                )
            ),
            'conditions' => array(
                'UserLine.user_id' => $uId,
                'UserLine.status' => UserLine::STATUS_ENABLED,
                'OR' => array(
                    'UserLine.certifications > ' => 0,
                    'UserLine.trainings > ' => 0,
                ),
            ),
            'fields' => array(
                'moes.id as mid',
                'areas.id as aid',
                'u.nomina as payroll',
                'u.id',
                'UserLine.line_id',
                'UserLine.assign_date',
                'UserLine.days',
                'moes.name as moe',
                'areas.name as area',
                'lines.name as line',
                'categorizations.name as level',
                'categorizations.icon',
                'categorizations.colour',
                'UserLine.certifications as nCert',
                'UserLine.trainings as nTrain'
            )
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    public function getByUserAndSesionUser($userId, $userSessionId)
    {
        $filters = array(
            'fields' => array(
                'UserLine.id',
                'UserLine.user_id as user_id',
                'l.id as line_id',
                'l.name as line',
                'a.name as area',
                'UserLine.certifications',
                'UserLine.trainings',
                'UserLine.days',
                'UserLine.assign_date',
                'cat.colour as cat_colour',
                'cat.icon as cat_icon',
                'cat.certifications as cat_certifications',
                'cat.name as cat_name',
            ),
            'joins' => array(
                array(
                    'table' => 'lines',
                    'alias' => 'l',
                    'type' => 'INNER',
                    'conditions' => array(
                        'l.status' => Line::STATUS_ENABLED,
                        'l.id = UserLine.line_id',
                    ),
                ),
                array(
                    'table' => 'areas',
                    'alias' => 'a',
                    'type' => 'INNER',
                    'conditions' => array(
                        'a.status' => Area::STATUS_ENABLED,
                        'a.id = l.area_id',
                    ),
                ),
                array(
                    'table' => 'user_areas',
                    'alias' => 'ua',
                    'type' => 'INNER',
                    'conditions' => array(
                        'ua.status' => UserArea::STATUS_ENABLED,
                        'ua.area_id = a.id',
                        'ua.user_id' => $userSessionId,
                    ),
                ),
                array(
                    'table' => 'categorizations',
                    'alias' => 'cat',
                    'type' => 'INNER',
                    'conditions' => array(
                        'UserLine.level = cat.id',
                    ),
                ),
            ),
            'conditions' => array(
                'UserLine.user_id' => $userId,
                'UserLine.status' => self::STATUS_ENABLED
            ),
            'order' => array(
                '(UserLine.certifications > 0 OR UserLine.trainings > 0) DESC',
                'area ASC',
                'line ASC',
            ),
            'group' => array(
                'l.id',
                'l.name',
                'a.name',
                'UserLine.certifications',
                'UserLine.trainings',
                'UserLine.assign_date',
            ),
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    /**
     * Actualizamos la fecha de ingreso a la linea
     * @param $userId
     * @param $lineId
     * @param $fields
     */
    public function updateUserLine($fields, $userId, $lineId)
    {
        $filters = array(
            'user_id' => $userId,
            'line_id' => $lineId,
            'status' => self::STATUS_ENABLED,
        );
        $this->updateAll($fields, $filters);
    }


    /**
     * Obtiene todos los cursos generales programados y los cursos disponibles de la categorizacion
     * siguiente a la que actualmente tiene el usuario.
     *
     * @param $userId
     * @return array
     */
    public function getSchedulesEnabledByLineByUser($userId) {
        $filters = array(
            'fields' => array(
                's.id as value',
                't.name as text',
                'r.name as room',
                '(s.room_capacity - s.users_registered) as capacity',
                's.start as start',
            ),
            'joins' => array(
                array(
                    'table' => 'categorizations',
                    'type' => 'INNER',
                    'alias' => 'c',
                    'conditions' => array(
                        'c.id = UserLine.level',
                        'c.status' => Categorization::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'categorizations',
                    'type' => 'INNER',
                    'alias' => 'c2',
                    'conditions' => array(
                        'c2.orden = c.orden+1',
                        'c2.status' => Categorization::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'tests',
                    'type' => 'INNER',
                    'alias' => 't',
                    'conditions' => array(
                        '(t.id = c2.test_id OR t.type = 1)',
                        't.status' => Test::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'schedules',
                    'type' => 'INNER',
                    'alias' => 's',
                    'conditions' => array(
                        's.test_id = t.id',
                        's.closed' => Schedule::NO_CLOSED,
                        's.status' => Schedule::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'rooms',
                    'type' => 'INNER',
                    'alias' => 'r',
                    'conditions' => array(
                        'r.id = s.room_id',
                        'r.status' => Room::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'user_tests',
                    'type' => 'LEFT',
                    'alias' => 'ut',
                    'conditions' => array(
                        'ut.qualification IS NULL',
                        'ut.schedule_id = s.id',
                        'ut.user_id' => $userId,
                        'ut.status'=> UserTest::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'user_tests',
                    'type' => 'LEFT',
                    'alias' => 'ut2',
                    'conditions' => array(
                        'ut2.qualification IS NULL',
                        'ut2.user_id' => $userId ,
                        'ut2.status'=> UserTest::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'schedules',
                    'type' => 'LEFT',
                    'alias' => 's2',
                    'conditions' => array(
                        's2.id = ut2.schedule_id',
                        's2.status' => Schedule::STATUS_ENABLED
                    )
                )
            ),
            'group' => array('s.id'),
            'order' => array('t.type'),
            'conditions' => array(
                'UserLine.user_id' => $userId,
                '( UserLine.certifications > 0 OR UserLine.trainings > 0 )',
                's.start >= CURDATE()',
                'ut.id is NULL',
                '(s2.test_id is NULL OR s2.test_id != s.test_id)',
                'UserLine.status' => self::STATUS_ENABLED
            )
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    public function getSummaryForKardex($userId) {
        $filters = array(
            'fields' => array(
                'm.name as moe',
                'a.name as area',
                'l.name as line',
                'UserLine.certifications as certs',
                'UserLine.trainings as trains',
                'c.icon as level',
                'c.colour as color'
            ),
            'joins' => array(
                array(
                    'table' => 'categorizations',
                    'type' => 'INNER',
                    'alias' => 'c',
                    'conditions' => array(
                        'c.id = UserLine.level',
                        'c.status' => Categorization::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'lines',
                    'type' => 'INNER',
                    'alias' => 'l',
                    'conditions' => array(
                        'l.id = UserLine.line_id',
                        'l.status' => Line::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'areas',
                    'alias' => 'a',
                    'type' => 'inner',
                    'conditions' => array(
                        'a.id = l.area_id',
                        'a.status' => Area::STATUS_ENABLED
                    )
                ),
                array(
                    'table' => 'moes',
                    'alias' => 'm',
                    'type' => 'inner',
                    'conditions' => array(
                        'm.id = a.moe_id',
                        'm.status' => Moe::STATUS_ENABLED
                    )
                ),
            ),
            'conditions' => array(
                'UserLine.user_id' => $userId,
                '(UserLine.certifications > 0 OR UserLine.trainings > 0)',
                'UserLine.status' => self::STATUS_ENABLED
            ),
            'order' => array(
                'assign_date ASC'
            )
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }
}
